<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-05
 * Time: 17:06
 */

namespace App\Http\Controllers\Api\V1\Manager\Mall;


use App\Http\Controllers\Controller;
use App\Models\Commodity;
use App\Models\CommodityCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CategoryController extends Controller
{
    public function index()
    {

        $data = CommodityCategory::orderBy('sort')->get();
        return $this->apiResponse($data);
    }

    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'categoryId'    =>   'integer',
            'categoryName'  =>   'required',
            'categoryIcon'          =>   'required'
        ]);
        if($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $categoryId = $data['categoryId'];
        unset($data['categoryId']);
        if($categoryId){//修改
             $status = CommodityCategory::where('categoryId',$categoryId)->update($data);
        }else{
            $status = CommodityCategory::where('categoryName',$data['categoryName'])->first();
            $num = CommodityCategory::select()->count();
            if($status){
                return $this->apiResponse('', config('errorCode.CATEGORYNAME_ADD_FAILED'));
            }
            $data['sort'] = $num+1;
            $data['createTime'] = date('Y-m-d H:i:s');
            $status = CommodityCategory::create($data);
        }
        if($status){//新增成功


            return $this->apiResponse(true);
        }else{
            return $this->apiResponse('', config('errorCode.CATEGORY_ADD_FAILED'));
        }
    }

    public function destroy($categoryId)
    {
        $status = Commodity::where('categoryId',$categoryId)->first();
        if($status){
            return $this->apiResponse('', config('errorCode.CATEGORY_DELETE_FAILED'));
        }
        $sort =  CommodityCategory::find($categoryId);
        CommodityCategory::where('sort','>',$sort['sort'])->decrement('sort',1);

        $status = CommodityCategory::destroy($categoryId);
        if($status){//删除成功
            return $this->apiResponse(true);
        }else{
           return $this->apiResponse('', config('errorCode.CATEGORY_NOR_FAILED'));
        }
    }

    public function update(Request $request)
    {
        $data = $request->list;
        $data = json_decode($data);
        foreach ($data as $k=>$v){
            CommodityCategory::where('categoryId',$v->categoryId)->update(['sort'=>$v->sort]);
        }
        return $this->apiResponse('');
    }
}